package com.zt.bus.line.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zt.bus.constant.BusConstant;
import com.zt.bus.line.inter.DispatchMapper;
import com.zt.bus.line.model.Dispatch;
import com.zt.bus.line.model.LinePlan;
import com.zt.bus.line.model.Vehicle;
import com.zt.bus.order.inter.OrderDetailMapper;
import com.zt.bus.order.model.Order;
import com.zt.bus.order.model.OrderDetail;
import com.zt.bus.order.service.OrderService;
import com.zt.bus.sms.service.SendCodeService;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.DateUtil;
import com.zt.util.PropertiesUtil;
import com.zt.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class DispatchService extends BaseService {

	@Autowired
	private DispatchMapper dispatchMapper;
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	@Autowired
	private LinePlanService linePlanService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private SendCodeService sendCodeService;

	 // 方案调度短信模板id
	public static final String PLAN_ALLOCATION = PropertiesUtil.getProperty("plan_allocation");

	/**
	 * 查询
	 *
	 * @param reqBean
	 * @return
	 */
	public JSONObject findDispatch(ReqBean reqBean) {
		SqlBuilder sqlBuilder = new SqlBuilder("", new Object[0]);
		return this.queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
	}

	/**
	 * 方案调度
	 * 分配完成后，给用户发送短信
	 * 
	 * @param reqBean
	 */
	public void addDispatch(String lineId, String planId, String lineName, Date departDate, String userId,
			JSONArray driverArray, JSONArray vehicleArray) {
		Date dateTime = new Date();
		LinePlan linePlan = linePlanService.getById(planId);
		if (linePlan == null) {
			throw new BusinessException("方案不存在");
		}
		// 保存之前先清空之前的配置
		dispatchMapper.deleteByPlanIdAndDepartDate(planId, departDate);
		String driverInfo = "";// 司机信息
		String vehicleInfo = "";// 车辆信息
		for (int i = 0; i < driverArray.size(); i++) {
			JSONObject driverJson = driverArray.getJSONObject(i);
			Dispatch dispatch = new Dispatch();
			dispatch.setId(intIncrementId("DZ_DISPATCH", "ID"));// 手动设置Id
			dispatch.setLineId(lineId);
			dispatch.setPlanId(planId);
			dispatch.setLineName(lineName);
			dispatch.setDriverNo(driverJson.getString("driverNo"));
			dispatch.setDriverPhone(driverJson.getString("driverPhone"));
			dispatch.setDriverName(driverJson.getString("driverName"));
			dispatch.setVehicleNo(vehicleArray.getJSONObject(i).getString("vehicleNo"));
			dispatch.setDepartDate(departDate);
			dispatch.setOperator(userId);
			dispatch.setMakeTime(dateTime);
			dispatch.setModifyTime(dateTime);
			dispatchMapper.insert(dispatch);
			driverInfo += dispatch.getDriverName() + "(" + dispatch.getDriverPhone() + ")" + "、";
			vehicleInfo += dispatch.getVehicleNo() + "、";
		}
		driverInfo = driverInfo.substring(0, driverInfo.length() - 1);
		vehicleInfo = vehicleInfo.substring(0, vehicleInfo.length() - 1);
		
		// 通过方案id找到订单信息
		List<Order> orderList = orderService.getByPlanId(planId);
		// 查询该方案当天全部的订单明细信息
		List<OrderDetail> orderDetailList = orderDetailMapper.selectByPlanIdAndRideDate(planId, departDate);
		Map<String, OrderDetail> maps = new HashMap<String, OrderDetail>();
		for (OrderDetail orderDetail : orderDetailList) {
			if (BusConstant.OrderDetailStatus.PAYMENT_SUCCESSFUL.equals(orderDetail.getStatus())) {
				maps.put(orderDetail.getOrderId(), orderDetail);
			}
		}
		JSONObject json = new JSONObject();
		json.put("departTime", DateUtil.formatDate(departDate) + " " + linePlan.getDepartTime());
		//Map<String,String> phoneMaps = new HashMap<String,String>();
		for (Order order : orderList) {// 一个手机号可以重复订
			OrderDetail detail = maps.get(order.getId());
			if (detail == null) {// 该订单当天没有需要乘车的乘客
				System.out.println("订单" + order.getId() + "在" + DateUtil.formatDate(departDate) + "没有需要乘车的乘客");
				continue;
			}
			// 短信内容
			String info = lineName + "线路(订单号:"+order.getId()+")已分配司机和车辆(司机:" + driverInfo + ";车辆:" + vehicleInfo + ")";
			json.put("msgInfo", info);
			String bookUserPhone = order.getBookUserPhone();
			/*if(phoneMaps.containsKey(bookUserPhone)){
				System.out.println("该手机号("+bookUserPhone+")短信已发送!");
			}else {
				phoneMaps.put(bookUserPhone, "短信已发送!");*/
				sendCodeService.sendSms(order.getId(),bookUserPhone, json.toString(), "方案调度短信提醒", PLAN_ALLOCATION);
			//}
		}
	}

	/**
	 * 获得方案某天对应的司机信息
	 * 
	 * @param planId
	 * @param departDate
	 *            发车日期
	 * @return
	 */
	public List<Dispatch> getByPlanIdAndDepartDate(String planId, Date departDate) {
		if (StringUtil.isEmpty(planId)) {
			throw new BusinessException("参数错误");
		}
		return dispatchMapper.selectByPlanIdAndDepartDate(planId, departDate);
	}

	/**
	 * 修改
	 *
	 * @param reqBean
	 */
	public void updatePlanDriver(ReqBean reqBean) {
		String id = reqBean.getInfo("id");
		if (StringUtil.isEmpty(id)) {
			throw new BusinessException("获取主键失败");
		}
		Dispatch dispatch = getDispatch(reqBean);
		dispatchMapper.updateByPrimaryKeySelective(dispatch);
	}

	/**
	 * 删除
	 *
	 * @param reqBean
	 */
	public void removeDispatch(ReqBean reqBean) {
		String id = reqBean.getInfo("id");
		if (StringUtil.isEmpty(id)) {
			throw new BusinessException("获取主键失败");
		}
		dispatchMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 从表单获取对象
	 *
	 * @param reqBean
	 * @return
	 */
	private Dispatch getDispatch(ReqBean reqBean) {
		Dispatch dispatch = new Dispatch();

		dispatch.setId(reqBean.getInfo("id"));
		dispatch.setPlanId(reqBean.getInfo("planId"));
		dispatch.setLineId(reqBean.getInfo("lineId"));
		dispatch.setLineName(reqBean.getInfo("lineName"));
		dispatch.setDriverNo(reqBean.getInfo("driverNo"));
		dispatch.setDriverName(reqBean.getInfo("driverName"));
		dispatch.setDepartDate(DateUtil.parseDateTime(reqBean.getInfo("departDate")));
		dispatch.setOperator(reqBean.getUserId());
		dispatch.setMakeTime(DateUtil.parseDateTime(reqBean.getInfo("makeTime")));
		dispatch.setModifyTime(new Date());
		dispatch.setRemark(reqBean.getInfo("remark"));

		return dispatch;
	}

}